package com.proactive.webapp.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.proactive.webapp.dao.CourseCollectDAO;
import com.proactive.webapp.dao.DesignCollectDAO;
import com.proactive.webapp.dao.MemberDAO;
import com.proactive.webapp.dao.MenuDAO;
import com.proactive.webapp.dao.WorksheetCategoryDAO;
import com.proactive.webapp.dao.WorksheetCollectDAO;
import com.proactive.webapp.dao.WorksheetContentDAO;
import com.proactive.webapp.dao.WorksheetDAO;
import com.proactive.webapp.dao.WorksheetTagDAO;
import com.proactive.webapp.entity.CourseCollect;
import com.proactive.webapp.entity.DesignCollect;
import com.proactive.webapp.entity.Member;
import com.proactive.webapp.entity.Menu;
import com.proactive.webapp.entity.Worksheet;
import com.proactive.webapp.entity.WorksheetCategory;
import com.proactive.webapp.entity.WorksheetCollect;
import com.proactive.webapp.entity.WorksheetContent;
import com.proactive.webapp.entity.WorksheetTag;
import com.proactive.webapp.form.WorksheetForm;
import com.proactive.webapp.util.DateConversion;
import com.proactive.webapp.util.FileUtil;
import com.proactive.webapp.util.MenuUtil;
import com.proactive.webapp.util.PageCount;

@Controller
public class MemberWorksheetController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");

	@RequestMapping(value = "/addWorksheetCont", method = RequestMethod.GET)
	public ModelAndView addWorksheetCont(HttpSession session) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			model.setViewName("addWorksheet");
			List<WorksheetCategory> category1List = new ArrayList<WorksheetCategory>();
			List<WorksheetTag> tagList = new ArrayList<WorksheetTag>();
			WorksheetCategoryDAO worksheetCategoryDAO = (WorksheetCategoryDAO) context.getBean("worksheetCategoryDAO");
			WorksheetTagDAO worksheetTagDAO = (WorksheetTagDAO) context.getBean("worksheetTagDAO");
			category1List = worksheetCategoryDAO.getList();
			tagList = worksheetTagDAO.getTop(10, category1List.get(0).getId());
			List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
			model.addObject("menuList", menuList);
			model.addObject("category1", category1List);
			model.addObject("tag", tagList);
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/addWorksheet", method = RequestMethod.POST)
	public ModelAndView addWorksheet(@ModelAttribute WorksheetForm worksheetForm, HttpSession session) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			WorksheetDAO worksheetDAO = (WorksheetDAO)context.getBean("worksheetDAO");
			WorksheetContentDAO worksheetContentDAO = (WorksheetContentDAO)context.getBean("worksheetContentDAO");
			Worksheet worksheet = worksheetForm.getWorksheet();
			List<WorksheetContent> contentList = worksheetForm.getContentList();
			worksheet.setAccount(loginMember.getAccount());
			worksheet.setContent(StringEscapeUtils.escapeHtml(worksheet.getContent()));
			int worksheetID = worksheetDAO.insert(worksheet);
			for (WorksheetContent worksheetContent : contentList) {
				if(worksheetContent.getTitle()!=null){
					worksheetContent.setAccount(loginMember.getAccount());
					worksheetContent.setWid(worksheetID);
					worksheetContent.setContent(StringEscapeUtils.escapeHtml(worksheetContent.getContent()));
					worksheetContentDAO.insert(worksheetContent);
				}
			}
			
			WorksheetTagDAO worksheetTagDAO = (WorksheetTagDAO) context.getBean("worksheetTagDAO");	
			String[] tags = worksheet.getTags().split(",");
			for(String tagName : tags){
				if(!tagName.equals("")){
					WorksheetTag worksheetTag = new WorksheetTag();
					worksheetTag.setWid(worksheetID);
					worksheetTag.setTag(tagName);
					worksheetTagDAO.insert(worksheetTag);
				}
			}
			model.setViewName("redirect:/showWorksheet?id="+worksheetID);
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/memberWorksheet", method = RequestMethod.GET)
	public ModelAndView getMemberWorksheetList(HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView();
		Member loginMember = (Member)session.getAttribute("loginMember");
		if (request.getParameter("id") != null) {
			MemberDAO memberDAO = (MemberDAO) context.getBean("memberDAO");
			WorksheetDAO worksheetDAO = (WorksheetDAO) context.getBean("worksheetDAO");
			Member member = new Member();			
			List<Worksheet> worksheetList = new ArrayList<Worksheet>();
			
			String memberNO = request.getParameter("id");
			int pageNow = request.getParameter("p")==null?1:Integer.parseInt(request.getParameter("p"));
			
			member.setMemberNO(memberNO);
			member = memberDAO.getByMemberNO(member);//用memberNO取得memberAccount
			if(member.getAccount()!=null){
				
				if(loginMember != null)
					member = memberDAO.getByLogin(member, loginMember.getAccount());//取得member資料
				int count = 0;
				if(member.isMyselfFlag())
					count = worksheetDAO.countTotalByWriter(member.getAccount());
				else
					count = worksheetDAO.countTotalByMember(member.getAccount());
				
				//set pager
				int pageSize = 6;
				String pageUrl = "memberWorksheet";
				String pageEndUrl1 = "&id="+memberNO;
				PageCount pageCount = new PageCount(pageNow, pageSize, count, pageUrl, pageEndUrl1);
				pageCount.calculate();
				
				if(member.isMyselfFlag())
					worksheetList = worksheetDAO.getListByWriter(member.getAccount(), pageCount.getStart(), pageSize);
				else
					worksheetList = worksheetDAO.getListByMember(member.getAccount(), pageCount.getStart(), pageSize);
				
				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				
				//set model
				model.addObject("page", pageCount);
				model.addObject("member", member);
				model.addObject("worksheetList", worksheetList);
				model.addObject("menuList", menuList);
				model.setViewName(loginMember!=null?"memberWorksheet1":"memberWorksheet2");
			
			}
			else
				model.setViewName("redirect:/");
			
		} 
		else
			model.setViewName(loginMember!=null?"redirect:/memberWorksheet?id="+loginMember.getMemberNO():"redirect:/login");

		
		return model;
	}
	
	@RequestMapping(value = "/actWorksheet", method = RequestMethod.POST)
	public ModelAndView actWorksheet(int id, String act, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){//檢查登入
			WorksheetDAO worksheetDAO = (WorksheetDAO) context.getBean("worksheetDAO");
			Worksheet worksheet = new Worksheet();
			worksheet.setId(id);
			worksheet = worksheetDAO.getByWriter(worksheet);
			if(worksheet.getAccount().equals(loginMember.getAccount())){//檢查是否為作者
				if(act.equals("delete")){
					worksheet.setStatus(3);
				}
				else if(act.equals("show")){
					worksheet.setStatus(1);
				}
				else if(act.equals("hide")){
					worksheet.setStatus(2);
				}
				worksheetDAO.updateStatus(worksheet);
				model.setViewName("redirect:"+request.getHeader("referer"));
			}
			else 
				model.setViewName("redirect:/memberWorksheet");
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/modiWorksheetCont", method = RequestMethod.GET)
	public ModelAndView modiWorksheetCont(HttpSession session, int id) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			WorksheetDAO worksheetDAO = (WorksheetDAO) context.getBean("worksheetDAO");
			Worksheet worksheet = new Worksheet();
			worksheet.setId(id);
			worksheet = worksheetDAO.getByWriter(worksheet);
			if(worksheet.getAccount().equals(loginMember.getAccount())){
				model.setViewName("modiWorksheet");
				List<WorksheetCategory> category1List = new ArrayList<WorksheetCategory>();
				List<WorksheetContent> contentList = new ArrayList<WorksheetContent>(); 
				List<WorksheetTag> tagList = new ArrayList<WorksheetTag>();
				List<WorksheetTag> tags = new ArrayList<WorksheetTag>();
				String tagString = "";
				WorksheetContentDAO worksheetContentDAO = (WorksheetContentDAO) context.getBean("worksheetContentDAO");
				WorksheetCategoryDAO worksheetCategoryDAO = (WorksheetCategoryDAO) context.getBean("worksheetCategoryDAO");
				WorksheetTagDAO worksheetTagDAO = (WorksheetTagDAO) context.getBean("worksheetTagDAO");
				contentList = worksheetContentDAO.getList(id);
				category1List = worksheetCategoryDAO.getList();
				tagList = worksheetTagDAO.getTop(10, worksheet.getCategoryID());
				tags = worksheetTagDAO.getListByWorksheetID(id);
				for (int i=0; i<tags.size(); i++) {
					WorksheetTag tag = tags.get(i);
					tagString += tag.getTag();
					if(i < tags.size())
						tagString += ",";
				}
				for(int j=0; j<category1List.size(); j++){
					if(category1List.get(j).getId() == worksheet.getCategoryID())
						category1List.get(j).setClassString("selected");
				}
				
				worksheet.setTags(tagString);

				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				model.addObject("menuList", menuList);
				model.addObject("contentList", contentList);
				model.addObject("category1", category1List);
				model.addObject("tag", tagList);
				model.addObject("worksheet", worksheet);
			}
			else
				model.setViewName("redirect:/worksheet");
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/modiWorksheet", method = RequestMethod.POST)
	public ModelAndView modiWorksheet(@ModelAttribute WorksheetForm worksheetForm, HttpSession session) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			WorksheetDAO worksheetDAO = (WorksheetDAO)context.getBean("worksheetDAO");
			WorksheetContentDAO worksheetContentDAO = (WorksheetContentDAO) context.getBean("worksheetContentDAO");
			Worksheet oldWorksheet = new Worksheet();
			Worksheet worksheet = worksheetForm.getWorksheet();
			List<WorksheetContent> contentList = worksheetForm.getContentList();
			oldWorksheet.setId(worksheet.getId());
			oldWorksheet = worksheetDAO.getByWriter(oldWorksheet);
			if(oldWorksheet.getAccount().equals(loginMember.getAccount())){
				worksheet.setAccount(loginMember.getAccount());			
				worksheet.setContent(StringEscapeUtils.escapeHtml(worksheet.getContent()));	
				worksheetDAO.update(worksheet);
				
				int worksheetID = worksheet.getId();
				for (WorksheetContent worksheetContent : contentList) {
					if(worksheetContent.getTitle()!=null){
						if(worksheetContent.getId() != 0){
							worksheetContent.setContent(StringEscapeUtils.escapeHtml(worksheetContent.getContent()));
							worksheetContentDAO.update(worksheetContent);
						}
						else{
							worksheetContent.setAccount(loginMember.getAccount());
							worksheetContent.setWid(worksheetID);
							worksheetContent.setContent(StringEscapeUtils.escapeHtml(worksheetContent.getContent()));
							System.out.println(worksheetContent.getContent());
							worksheetContentDAO.insert(worksheetContent);
						}
					}
				}
				
				WorksheetTagDAO worksheetTagDAO = (WorksheetTagDAO) context.getBean("worksheetTagDAO");	
				worksheetTagDAO.delete(worksheet.getId());
				String[] tags = worksheet.getTags().split(",");
				for(String tagName : tags){
					if(!tagName.equals("")){
						WorksheetTag worksheetTag = new WorksheetTag();
						worksheetTag.setWid(worksheet.getId());
						worksheetTag.setTag(tagName);
						worksheetTagDAO.insert(worksheetTag);
					}
				}
				
			}
			model.setViewName("redirect:/memberWorksheet?id="+loginMember.getMemberNO());
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/delWorksheetContent", method = RequestMethod.POST)
	public @ResponseBody void delWorksheetContent(int id, HttpSession session){
		Member loginMember = (Member)session.getAttribute("loginMember");
		if(loginMember != null){
			WorksheetContentDAO worksheetContentDAO = (WorksheetContentDAO) context.getBean("worksheetContentDAO");
			WorksheetContent worksheetContent = new WorksheetContent();
			worksheetContent.setId(id);
			worksheetContent = worksheetContentDAO.get(worksheetContent);
			if(worksheetContent.getAccount().equals(loginMember.getAccount())){
				worksheetContentDAO.delete(id);
			}
		}
	}
}
